from machine import Pin
import time
import network
import socket
import gc  # 添加垃圾回收模块

# 配置参数（可根据实际需求修改）
WIFI_SSID = "LAPTOP-D3RPTUAA 6358"
WIFI_PASSWORD = "19234949992.ch"
LED_PIN = 5  # LED指示灯引脚
HTML_FILE_PATH = "/index.html"  # HTML文件存储在SPIFFS文件系统中

def init_led(pin=LED_PIN):
    """初始化LED引脚，返回LED对象"""
    led = Pin(pin, Pin.OUT)
    return led

def connect_wifi(ssid, password, led):
    """连接WiFi网络，返回连接状态和IP地址（(成功标志, IP地址)）"""
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid, password)

    # 等待连接（带超时处理）
    timeout = 20  # 延长超时时间至20秒
    while timeout > 0:
        if wlan.isconnected():
            print("WiFi连接成功!")
            ip_addr = wlan.ifconfig()[0]
            print(f"IP地址: {ip_addr}")
            led.off()  # 连接成功：LED熄灭
            return (True, ip_addr)
        
        timeout -= 1
        led.on()  # 连接中：LED点亮
        time.sleep(1)
        print(f"等待连接...({timeout}秒)")

    # 连接超时处理
    print("WiFi连接超时!")
    led.on()  # 连接失败：LED常亮
    return (False, None)

def read_html_file():
    """从SPIFFS文件系统读取HTML文件内容（分块读取）"""
    try:
        with open(HTML_FILE_PATH, 'r') as f:
            html_content = ""
            while True:
                chunk = f.read(512)  # 每次读取512字节
                if not chunk:
                    break
                html_content += chunk
                gc.collect()  # 每读取一块触发垃圾回收
            print(f"HTML文件大小: {len(html_content)} 字节")
            return html_content
    except Exception as e:
        print(f"读取HTML文件失败: {e}")
        return None

def handle_client(cl):
    """处理客户端HTTP请求（使用文件流式传输）"""
    try:
        # 接收客户端请求数据
        request = cl.recv(1024)
        
        # 发送HTTP响应头
        cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
        
        # 流式传输HTML文件
        with open(HTML_FILE_PATH, 'r') as f:
            while True:
                chunk = f.read(512)  # 每次发送512字节
                if not chunk:
                    break
                cl.send(chunk)
                gc.collect()  # 每发送一块触发垃圾回收
        
    except Exception as e:
        print(f"处理客户端请求错误: {e}")
    finally:
        # 确保连接关闭
        if 'cl' in locals():
            cl.close()
        gc.collect()

def start_web_server(ip_addr):
    """启动Web服务器并处理客户端请求"""
    print(f'Web服务器已启动，访问: http://{ip_addr}')
    
    # 创建socket并绑定端口
    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 允许端口重用
    s.bind(addr)
    s.listen(1)  # 最多同时处理1个连接
    
    try:
        # 服务器主循环
        while True:
            cl, client_addr = s.accept()
            print(f'客户端连接来自: {client_addr}')
            handle_client(cl)
            gc.collect()  # 每次请求后回收内存
    except Exception as e:
        print(f"Web服务器错误: {e}")
    finally:
        # 确保socket关闭
        s.close()